package com.len.controller;

import java.io.IOException;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.len.base.BaseController;
import com.len.config.WebSocketServer;
import com.len.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

@CrossOrigin
@RestController
@RequestMapping("/portal/ws")
@Slf4j
public class WebSocketController extends BaseController<Object> {

	@GetMapping("/client/{userId}")
	public ModelAndView socket(@PathVariable String userId) {
		log.info("WebSocketController=======>>> socket method userId=" + userId);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/wsclient");
		modelAndView.addObject("userId", userId);
		return modelAndView;
	}

	// 推送数据接口
	@PostMapping("/client/push/{userId}")
	public JsonUtil pushToServer(@PathVariable String userId, String message) {
		log.info("WebSocketController=======>>> pushToServer method userId=" + userId);
		try {
			WebSocketServer.sendInfo(message, userId);
		} catch (IOException e) {
			e.printStackTrace();
			return JsonUtil.error(userId + "#" + e.getMessage());
		}
		return JsonUtil.success(userId);
	}

}
